package com.zhiwang.planet.ui.webview_ultimate.interceptors

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.webkit.WebView
import com.zhiwang.planet.App
import com.zhiwang.planet.di.component.DaggerUtilComponent
import com.zhiwang.planet.event.H5RewardEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.H5GameReq
import com.zhiwang.planet.ui.WebViewPageHandler
import com.zhiwang.planet.ui.webview_ultimate.InterceptorAdapter
import com.zhiwang.planet.util.SystemUtil.isAppInstalled
import com.zhiwang.planet.util.Toaster.message
import com.zhiwang.planet.util.Utils
import com.zhiwang.planet.util.arrange
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class DwInterceptor : InterceptorAdapter() {


    @Inject
    lateinit var restApi: RestApi


    init {

        DaggerUtilComponent.builder()
                .appComponent(App.instance.appComponent)
                .build()
                .inject(this)

    }

    var gameId: String = ""

    var intercept = false

    override fun onPageStart(webView: WebView) {
        val url = webView.url
        if (TextUtils.isEmpty(url).not() && url.startsWith("http://www.shandw.com/"))
            intercept = true

        if (TextUtils.isEmpty(url).not() && url.contains("/game") && url.contains("shandw")) {
            gameId = url.substring(url.indexOf("/game") + 6, url.indexOf(".html"))
            startTimer()
        } else if (TextUtils.isEmpty(url).not() && url.contains("mi/index")) {
            stopTimer()
        }
    }


    private var disposable: Disposable? = null


    private fun startTimer() {

        stopTimer()
        disposable = Observable.interval(0, 60, TimeUnit.SECONDS)
                .subscribeOn(io.reactivex.schedulers.Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    ping(null, false)
                }
    }

    private fun ping(handler: WebViewPageHandler?, end: Boolean) {

        restApi.postH5GameTime(H5GameReq(gameId, if (end) "end" else "ping"))
                .arrange(Consumer {

                    if (end) {
                        EventBus.getDefault().post(H5RewardEvent(it?.reward))
                        handler?.closePage()
                    }
                }, Consumer {


                }, Action {

                })
    }

    private fun stopTimer() {
        if (disposable?.isDisposed == false)
            disposable?.dispose()
    }


    private val TAG = "DwInterceptor"

    override fun shouldInterceptUrlLoading(webView: WebView, url: String): Boolean {

        Log.i(TAG, "shouldInterceptUrlLoading: $url")
        //处理支付宝微信支付

        if (handlePayReq(webView.context, webView, url)) {
            return true
        }

        return false
    }

    private fun handlePayReq(context: Context, view: WebView, url: String?): Boolean {
        // 如下方案可在非微信内部WebView的H5页面中调出微信支付

        if (url!!.startsWith("weixin://wap/pay?") || url.startsWith("alipay")) {
            try {
                val hasApp: Boolean = if (url.startsWith("weixin://wap/pay?")) {
                    isAppInstalled(context, "com.tencent.mm")
                } else {
                    (isAppInstalled(context, "com.alipay.android.app")
                            || isAppInstalled(context, "com.eg.android.AlipayGphone"))
                }
                if (hasApp) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(url)
                    context.startActivity(intent)
                } else {
                    message("客官，请先安装支付App哦~")
                }
                return true
            } catch (e: Exception) {
                e.printStackTrace()
                message("客官，请先安装支付App哦~")
            }
        }

        return false
    }


    override fun onGoBack(handler: WebViewPageHandler, webView: WebView): Boolean {
        if (TextUtils.isEmpty(gameId).not()) {
            ping(handler, true)
            return false
        }

        return false

    }


    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
    }


}